<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row>
        <!-- 添加分类按钮 -->
        <el-col :span="24">
          <div>
            <el-button type="primary" @click="addCategoriesDialog()"
              >添加分类</el-button
            >
          </div>
        </el-col>
        <!-- 表格区域 -->
        <el-col>
          <el-table
            :data="cateList"
            border
            stripe
            row-key="cat_id"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          >
            <el-table-column label="#" prop="layerIndex" width="100">
            </el-table-column>
            <el-table-column label="分类名称" prop="cat_name"></el-table-column>
            <el-table-column label="是否有效">
              <template slot-scope="scope">
                <i
                  class="el-icon-error"
                  style="color: red"
                  v-if="scope.row.cat_deleted"
                ></i>
                <i class="el-icon-success" style="color: lightgreen" v-else></i>
              </template>
            </el-table-column>
            <el-table-column label="排序">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
                <el-tag v-else-if="scope.row.cat_level === 1" type="success"
                  >二级
                </el-tag>
                <el-tag v-else-if="scope.row.cat_level === 2" type="warning"
                  >三级
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 编辑按钮 -->
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="changeCategoriesDialog(scope.row)"
                  >编辑
                </el-button>
                <!-- 删除按钮 -->
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteCategories(scope.row.cat_id)"
                  >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <!-- 分页区域 -->
        <el-col>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="querInfo.pagenum"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="querInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </el-col>
        <!-- 添加分类对话框 -->
        <el-dialog
          title="添加分类"
          :visible.sync="addCategoriesDialogVisible"
          @close="addCategoriesDialogClose"
          width="50%"
        >
          <!-- 添加分类表单 -->
          <el-form
            ref="addCategoRef"
            :model="addCategoObj"
            :rules="addCategoRules"
          >
            <el-form-item label="父级分类">
              <!-- 级联选择器 -->
              <!-- options指定数据源 -->
              <el-cascader
                placeholder="请选择，未选择默认为一级"
                v-model="selectedKeys"
                clearable
                :options="parentCateList"
                :props="{
                  expandTrigger: 'hover',
                  checkStrictly: true,
                  label: 'cat_name',
                  value: 'cat_id',
                }"
                @change="parentCategoChange"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="分类名称" prop="cat_name">
              <el-input v-model="addCategoObj.cat_name"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addCategoriesDialogVisible = false"
              >取 消</el-button
            >
            <el-button type="primary" @click="addCategories">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 编辑分类对话框 -->
        <el-dialog
          title="编辑分类"
          :visible.sync="changeCategoriesDialogVisible"
          width="50%"
        >
          <el-form
            ref="changeCategoriesFormRef"
            :model="changeCategoriesObj"
            :rules="addCategoRules"
          >
            <el-form-item label="分类名称" prop="cat_name">
              <el-input v-model="changeCategoriesObj.cat_name"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="changeCategoriesDialogVisible = false"
              >取 消</el-button
            >
            <el-button type="primary" @click="changeCategories"
              >确 定</el-button
            >
          </span>
        </el-dialog>
      </el-row>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 请求参数
      querInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 分类数据
      cateList: [],
      // 总数据条数
      total: 0,
      // 添加分类对话框开关
      addCategoriesDialogVisible: false,
      // 添加分类对象
      addCategoObj: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0
      },
      // 添加分类表单验证对象
      addCategoRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      // 父级分类列表
      parentCateList: [],
      // 级联选择框双向绑定数据
      selectedKeys: [],
      // 编辑分类对话框开关
      changeCategoriesDialogVisible: false,
      // 编辑分类对象
      changeCategoriesObj: {
        cat_name: ''
      },
      // 当前编辑分类id
      cat_id: 0
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取分类列表
    async getCateList () {
      const { data: res } = await this.$http.get('categories', { params: this.querInfo })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类列表失败！')
      }
      this.addlayerIndex(res.data.result)
      this.cateList = res.data.result
      this.total = res.data.total
      this.$message.success('获取分类列表成功！')
    },
    // 添加层级索引
    addlayerIndex (array) {
      array.forEach((item, index) => {
        item.layerIndex = ++index
        if (item.children) {
          this.addlayerIndex(item.children)
        }
      })
    },
    // 打开添加分类对话框，获取父级分类列表
    async addCategoriesDialog () {
      const { data: res } = await this.$http.get('categories', { params: { type: 2 } })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取父级分类列表失败！')
      }
      this.parentCateList = res.data
      this.$message.success('获取父级分类列表成功！')
      this.addCategoriesDialogVisible = true
    },
    // 父级分类选择变化赋值添加分类对象
    parentCategoChange () {
      console.log(this.selectedKeys)
      if (this.selectedKeys.length > 0) {
        // 层级赋值
        this.addCategoObj.cat_level = this.selectedKeys.length
        // 父级id赋值
        this.addCategoObj.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
      } else {
        this.addCategoObj.cat_level = 0
        this.addCategoObj.cat_pid = 0
      }
    },
    // 确认添加分类
    addCategories () {
      console.log(this.selectedKeys)
      console.log(this.addCategoObj)
      this.$refs.addCategoRef.validate(async valid => {
        if (!valid) { return this.$message.error('表单校验未通过') }
        console.log(this.addCategoObj)
        // 表单校验通过，发起网络请求
        const { data: res } = await this.$http.post('categories', this.addCategoObj)
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加分类失败！')
        }
        // 关闭弹窗
        this.addCategoriesDialogVisible = false
        // 刷新分类列表
        this.getCateList()
        this.$message.success('添加分类成功！')
      })
    },
    // 关闭添加分类对话框的回调,清空表单
    addCategoriesDialogClose () {
      this.$refs.addCategoRef.resetFields()
      this.addCategoObj.cat_pid = 0
      this.addCategoObj.cat_level = 0
      this.selectedKeys = []
    },
    // 打开编辑分类对话框
    changeCategoriesDialog (data) {
      this.cat_id = data.cat_id
      this.changeCategoriesObj.cat_name = data.cat_name
      this.changeCategoriesDialogVisible = true
    },
    // 确认编辑分类
    changeCategories () {
      this.$refs.changeCategoriesFormRef.validate(async valid => {
        console.log(valid)
        if (!valid) { return this.$message.error('表单校验未通过') }
        // 表单校验通过，发起网络请求
        const { data: res } = await this.$http.put('categories/' + this.cat_id, this.changeCategoriesObj)
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('更新分类失败！')
        }
        // 关闭弹窗
        this.changeCategoriesDialogVisible = false
        // 刷新分类列表
        this.getCateList()
        this.$message.success('更新分类成功！')
      })
    },
    // 根据id删除分类
    async deleteCategories (id) {
      // 弹框提示是否删除
      const confirmResult = await this.$confirm('此操作将删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      // 发起删除请求
      const { data: res } = await this.$http.delete('categories/' + id)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.getCateList()
      this.$message.success('删除成功')
    },
    // 监听pageSize改变
    handleSizeChange (newSize) {
      this.querInfo.pagesize = newSize
      this.getCateList()
    },
    // 监听currentPage 改变
    handleCurrentChange (newPage) {
      this.querInfo.pagenum = newPage
      this.getCateList()
    }
  }
}
</script>

<style scoped>
.el-cascader {
  width: 100%;
}
</style>
